<?php
//验证码类
namespace App\Think;

use EasySwoole\VerifyCode\Conf;
use EasySwoole\VerifyCode\VerifyCode;

use App\Think\Cache;

class Captcha {
      private $charset = 'abcdefghkmnprstuvwxyzABCDEFGHKMNPRSTUVWXYZ23456789'; //随机因子
      private $code;       //验证码
      private $codelen = 4;     //验证码长度
      private $prefix = 'cacheId:';

      protected static $instance;

      // 初始化
      public static function instance()
      {
          if (is_null(self::$instance)) self::$instance = new static();
          return self::$instance;
      }

      //对外显示验证码
      public function captcha_src($captcha_id='') {
        $code = $this->createCode();
        Cache::set($this->prefix.$captcha_id, $code, 60);

        $config = new Conf();
        $cls    = new VerifyCode($config);
        return $cls->DrawCode($code)->getImageByte();
      }  

      //验证码验证
      public function captcha_check($code='', $captcha_id=''){
          $value = Cache::get($this->prefix.$captcha_id);
          if(strtolower($code) == $value){
              Cache::set($this->prefix.$captcha_id, 1);
              return true;
          }
          return false;
      }

      //生成随机码
      private function createCode() {
        $code = '';
        $_len = strlen($this->charset)-1;
        for ($i=0;$i<$this->codelen;$i++) {
            $code .= $this->charset[mt_rand(0,$_len)];
        }
        return $code;
      }  


}
